<template>
    <!-- 操作按钮区 -->
    <div class="action-buttons">
      <el-button type="success" @click="batchSaveDetails" class="add-button">添加</el-button>
    </div>
    <!-- 查询条件部分 -->
    <div class="search-section">
      <el-form :inline="true" :model="prolist">
        <el-form-item label="质检工单主题">
          <el-input v-model="prolist.qualityWorkOrder" placeholder="输入质检工单主题"></el-input>
        </el-form-item>
        <el-form-item label="质检工单编号">
          <el-input v-model="prolist.qualityWorkOrderNumber" placeholder="输入质检工单编号"></el-input>
        </el-form-item>
        <el-form-item label="生成物品">
          <el-input v-model="prolist.GenerateItems" placeholder="输入生成物品"></el-input>
        </el-form-item>
        <el-form-item label="质检负责人">
          <el-input v-model="prolist.QualityPerson" placeholder="输入设备质检负责人"></el-input>
        </el-form-item>
        <el-form-item label="质检部门">
          <el-select 
            v-model="prolist.QualityDepartment" 
            placeholder="请选择质检部门" 
            clearable
            style="width: 200px;"
          >
            <el-option label="包装部" value="包装部"/>
            <el-option label="生产部" value="生产部"/>
            <el-option label="酵母部" value="酵母部"/>
            <el-option label="原料部" value="原料部"/>
            <el-option label="发酵部" value="发酵部"/>
          </el-select>
        </el-form-item>
         <el-form-item label="状态">
          <el-select 
            v-model="prolist.status" 
            placeholder="请选择质检状态" 
            clearable
            style="width: 200px;"
          >
            <el-option label="待质检" value="待质检"/>
            <el-option label="质检中" value="质检中"/>
            <el-option label="已完成" value="已完成"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="ShowMaterials" class="search-button">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <div class="page-title">
        <h2>质检申请列表</h2>
      </div>
      <div class="table-container">
        <el-table :data="planList" stripe ref="tableRef" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="qualityWorkOrderNumber" label="质检工单编号" />
          <el-table-column prop="qualityWorkOrder" label="质检工单名称" />
          <el-table-column prop="sourceWorkOrder" label="来源工单" />
          <el-table-column prop="generateItems" label="生产物品" />
          <el-table-column prop="qualityDepartment" label="质检部门" />
          <el-table-column prop="qualityPerson" label="质检负责人" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag
                :type="scope.row.status === '待质检'? 'danger' : 
                       scope.row.status === '质检中'? 'warning' : 
                       scope.row.status === '已完成'? 'success' : 'info'"
                size="small"
              >
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="processQuantity" label="工序数量" />
          <el-table-column label="操作" width="140">
            <template #default="scope">
              <el-button  type="primary" 
                link 
                @click="GetBYIdProductionPlanning(scope.row.qualityid)"
                v-if="scope.row.status !== '已完成'">编辑工单</el-button>
              <el-button type="info" link @click="GetBYIdProductionPlanning1(scope.row.qualityid)">查看详情页</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="page.pageindex"
          v-model:page-size="page.pageSize"
          :page-sizes="[4, 8, 15, 20]"
          :background="true"
          prev-text="上一页"
          next-text="下一页"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import router from '@/router';
  import axios from 'axios';

  // 定义搜索表单数据
  const prolist = ref({
    qualityWorkOrder:'',
    qualityWorkOrderNumber:'',
    GenerateItems:'',
    QualityPerson:'',
    QualityDepartment:'',
    status: '',
  });
  
  // 定义分页总数
  const total = ref({
    totalCount: 0,
    totalPage: 0,
  });
  
  // 定义分页对象
  const page = ref({
    pageindex: 1,
    pageSize: 5,
  });
  
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  };
  

  
  // 模拟生产计划列表数据
  const planList = ref([
    {
        "qualityid": '',
       "qualityWorkOrder": "",
        "qualityWorkOrderNumber": "",
        "sourceWorkOrder": "",
        "generateItems": "",
        "qualityPerson": "",
        "qualityDepartment": "",
        "processQuantity": '',
        status : '',
        "remarks": "",
        "isDel": false,
    }
  ]);
  
  // 表格引用
  const tableRef = ref(null);
  
  // 全选状态
  const allChecked = ref(false);
  
  // 选中的 ID 列表
  const checkedIds = ref([]);
  
  const ShowMaterials = () => {
    Materialread.get("f-read/api/Arrival/GetQualityLnspection", {
      params: {
        pageindex: page.value.pageindex,
        pageSize: page.value.pageSize,
        qualityWorkOrder: prolist.value.qualityWorkOrder,
        qualityWorkOrderNumber: prolist.value.qualityWorkOrderNumber,
        GenerateItems: prolist.value.GenerateItems, 
        QualityPerson: prolist.value.QualityPerson,
        QualityDepartment: prolist.value.QualityDepartment,
        MakingDate: prolist.value.MakingDate,
        status: prolist.value.status,
      }
    }).then((res) => {
      planList.value = res.data.data.list.filter(item => !filterStatus.value || item.status === filterStatus.value);
      console.log("显示数据", res.data.data);
  
      total.value.totalCount = res.data.data.totalCount;
      total.value.totalPage = res.data.data.totalPage;
      // 重置全选状态和选中的 ID 列表
      allChecked.value = false;
      checkedIds.value = [];
      console.log(res.data.data);
    }).catch((error) => {
      console.error('接口请求失败:', error);
      ElMessage.error('数据获取失败，请稍后重试');
    });
  };
  
// 编辑跳转修改
const GetBYIdProductionPlanning = (qualityid) => {
    router.push({
        name: 'UpdateQualityLnspection',
        query: {
            qualityid: qualityid
        }
    });
    console.log(qualityid);
};
// 查看
const GetBYIdProductionPlanning1 = (qualityid) => {
    router.push({
        name: 'FTQualityLnspection',
        query: {
            qualityid: qualityid
        }
    });
    console.log(qualityid);
};
//跳转添加
const batchSaveDetails = () => {
     router.push({
        name: 'AddQualityLnspection',
        
    });
    // console.log(feedingId);
}
  
  const DeleteProductionPlanning = async (qualityid) => {
    try {
      const confirmResult = await ElMessageBox.confirm(
        '确认删除该条记录？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      if (confirmResult === 'confirm') {
        const response = await Materialwrite.post(
          `f-write/api/Arrival/DelQualityLnspection`,
          { qualityid: qualityid.toString() }, // 修改这里，将参数放在请求体中
          {
            params: {Qualityid: qualityid.toString()} // 这里保持为空，因为参数已经在请求体中
          }
        );
        if (response.data.code === 200) {
          ElMessage.success('删除成功');
          ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
        } else {
          ElMessage.error(`删除失败：${response.data.message}`);
        }
      }
    } catch (error) {
      if (error!== 'cancel') {
        console.error('删除错误:', error);
        ElMessage.error('删除失败，请检查网络或联系管理员');
      }
    }
  };
  const handleSizeChange = (val) => {
    page.value.pageSize = val;
    ShowMaterials();
  };
  
  const handleCurrentChange = (val) => {
    page.value.pageindex = val;
    ShowMaterials();
  };
  

  onMounted(() => {
    ShowMaterials();
   
  });
  </script>
  
  <style scoped>
  body {
    font-family: 'Arial', sans-serif;
    background-color: #f0f2f5;
    margin: 0;
    padding: 0;
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    padding: 20px;
  }
  
  .import-button,
  .add-button,
  .search-button {
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .import-button {
    border: 1px solid #ccc;
    background-color: white;
    color: #333;
    margin-right: 10px;
  }
  
  .add-button {
    border: none;
    background-color: #42b983;
    color: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .search-button {
    border: 1px solid #42b983;
    background-color: white;
    color: #42b983;
  }
  
  .search-section {
    background-color: white;
    padding: 40px;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
    margin: 0 20px 20px;
  }
  
  .page-title {
    text-align: center;
    color: #2c3e50;
    margin-bottom: 20px;
  }
  
  .table-container {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
    margin: 0 20px;
    max-height: 400px;
    overflow-y: auto;
  }
  
  .el-table {
    width: 100%;
    border-collapse: collapse;
  }
  
  .el-table__header-wrapper {
    background-color: #f4f4f4;
  }
  
  .el-table__header th {
    padding: 10px;
    text-align: left;
    border-bottom: 1px solid #ccc;
    color: #333;
  }
  
  .el-table__body td {
    padding: 10px;
    border-bottom: 1px solid #eee;
    color: #666;
  }
  
  .edit-button,
  .delete-button {
    color: #42b983;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease, color 0.3s ease;
  }
  
  .edit-button:hover {
    background-color: #f0f9eb;
  }
  
  .delete-button:hover {
    color: red;
  }
  
  .el-pagination {
    display: flex;
    justify-content: center;
    margin: 20px 0;
  }
  </style>